VITEZOVI MiG-29 MFD ADD-ON - MAINTAINER NOTES  (state of v1.7.7, Nov 2026)
=========================================================================

Who this is for: whoever has to fix or update the add-on later (after a
DCS patch, a new KRN version, or a new map). Read sections 1-3 first.

The add-on sits on top of "MiG-29A(M) Cockpit Modernization - KRN MODS
V1.0.3" for the full-fidelity MiG-29 module (unit type "MiG-29 Fulcrum").
KRN's own files are mostly obfuscated; we only add a few lines to them.

Folders (all under Saved Games\DCS):
  Mods\tech\MiG-29A(M) Cockpit Modernization - KRN MODS V1.0.3\   the mod
  Scripts\MiG29DL_Export.lua                                    export
  Scripts\Hooks\MiG29DL_Hook.lua                                hook
  MiG29-DL-Addon\source\           copies of our files + tools (this note)
  MiG29-DL-Addon\backup_original\  KRN's untouched originals of every file
                                   we changed (+ the original Export.lua)
  MiG29-DL-Addon\flight.txt        the player's saved FLT members
In the "Vitezovi MiG-29 MFD v1.4" folder (Desktop) the same material is in
Maintainer\tools (the Python tools) and Maintainer\KRN_originals (= backup_original).


0. THE ADD-ON PACKAGE (public release, v1.7)
---------------------------------------------
Since v1.7 the add-on ships WITHOUT any of KRN's files (agreed with KRN:
his mod stays his own download, ours installs on top). Package:
  INSTALL.bat / UNINSTALL.bat   run installer\vitezovi_install.ps1
                                (Windows PowerShell 5.1, -Uninstall)
  installer\krn_patch.json      what to change in KRN's V1.0.3 files:
       files  SHA-256 of each KRN original (+ "norm_sha256" of the text
              with LF line ends and the end trimmed, to recognise an
              earlier install), kind text / edm / png
       text   insertions: mode after / before an anchor (1-4 whole lines,
              unique in the file) or append; text = the lines to insert
       edm    UFCP.edm splice: 4-byte overwrites and byte inserts at offsets
              of the ORIGINAL file (+ overwrite_orig to undo it); result
              checked against result_sha256
       tiles  PNG tiles pasted at x / y into Shared_Material.png and
              Buttons.png (only the changed label areas)
  installer\VitezoviPatch.cs    PNG read / write, tile paste, EDM splice
                                (compiled by Add-Type; keep it C# 5)
  installer\tiles\              the label tiles
  files\KRN mod\                our files that go into KRN's folder
                                (Cockpit\Scripts\DL, our two .dds)
  files\Saved Games DCS\        export, hook, example DTC, missions
Install: find KRN (entry.lua declares "mig_29am"), for every file get KRN's
original (our backup, the file itself, the old MiG29-DL-Addon\backup_original,
or - for an earlier install - the file with our insertions taken out / the
EDM splice undone), keep it in Saved Games\DCS\Vitezovi-MFD-Addon\krn_backup,
patch into a temp folder, move into place, copy our files, add the
Export.lua line. Any file not recognised: stop, nothing changed.
Uninstall: put the backups back, remove our files and the Export line.
v1.7.2 installer rules (keep them):
  * A KRN file is only patched / restored when it is byte for byte KRN's
    V1.0.3 original or one of this add-on's own results (krn_patch.json
    keeps the result hashes of v1.7 to v1.7.3, with undo steps;
    PNGs by pixel hash because their bytes depend on the PC's .NET).
    Anything else (a newer KRN): install stops, nothing changed; uninstall
    leaves that file and lists it.
  * Saved Games comes from the registry (User Shell Folders, value
    {4C5C32FF-BB9D-43B0-B5B4-2D72E54EAAA4}), fallback %USERPROFILE%; every
    Saved Games\DCS* folder with KRN's mod is done. The .bat files pass
    %* on (-SavedGames <path> works).
  * Every path goes through .NET or -LiteralPath ("[ ]" in folder names).
  * Export.lua is edited as bytes: encoding, BOM and each line's ending
    stay as they were; only an uncommented copy of our line counts.
  * User settings live in Saved Games\DCS\Vitezovi-MFD-Addon\settings.lua
    (template made on install, never touched again). A dl_config.lua that
    differs from every shipped one (hashes in krn_patch.json) is kept as
    Vitezovi-MFD-Addon\dl_config_before_update.lua.
  * Each step has its own error message with what to do (Constrained
    Language Mode, Add-Type blocked, a locked file, read-only or UTF-16
    Export.lua, an incomplete package, odd textures).
Building a new release: change the files (sections below), apply them to a
copy of KRN's mod, then run tools\gen_patch.py (paths at its top: KRN's
original folder, the finished folder, the output) - it writes krn_patch.json
and the tiles and checks that they reproduce the finished files exactly.
For a new KRN version: new anchors / EDM offsets / hashes the same way
(patch_edm.py stops if KRN's model layout changed).

1. WHAT WE CHANGED IN KRN'S FILES (re-apply this after a KRN update)
---------------------------------------------------------------------
All paths relative to the mod folder. Every change is an added line or
block; nothing of KRN's was removed.

  Cockpit\Scripts\devices.lua
      added LAST (so KRN's device ids do not move):
        devices["MIG29_DL"] = counter()

  Cockpit\Scripts\device_init.lua
      added to the creators list:
        creators[devices.MIG29_DL] = {"avLuaDevice", LockOn_Options.script_path.."DL/dl_device.lua"}

  Cockpit\Scripts\materials.lua
      added after the textures:    pcall(dofile, LockOn_Options.script_path .. "DL/dl_textures.lua")
      added at the very end:       pcall(dofile, LockOn_Options.script_path .. "DL/dl_fonts.lua")

  Cockpit\Scripts\MFD\pages\obf_K7j9M2sW5yZ8bB1cD4fG7hJ0kL3nO6pQ.lua
      (KRN's last MFD page file) added at the end, so our pages draw on top:
        pcall(dofile, LockOn_Options.script_path .. "DL/dl_page.lua")

  Cockpit\Scripts\UFCP\base_page.lua
      added at the end (UFCP line while typing on the keypad, e.g. "BNG 15_"):
        pcall(dofile, LockOn_Options.script_path .. "DL/dl_ufcp.lua")

  Cockpit\Scripts\clickabledata.lua
      added at the end, before KRN's final "for i,o in pairs(elements)" loop:
      MFD-B1 B2 B4 B5, MFD-R1..R5, MFD-T1..T5, MFD-BRT, MFD-DN, MFD-SYM,
      (v1.7) MFD-PWR (display POWER, command 1127, arg 101), the press
      animation args of KRN's MFD-1..5 / MFD-8 set to their own buttons,
      and (v1.4) overrides of KRN's UFCP BTN-11 (MRK -> 6041),
      BTN-12 (DVR, now DIR -> 6043), BTN-15 (FLT/MENU, now NAV -> 6042)
      (copy the block from source\clickabledata.lua).

  Textures\Shared_Material.png   (v1.4)
      UFCP key labels "DVR" -> "DIR", "FLT/MENU" -> "NAV" (all 5 copies of
      the labels in the texture, some sideways / mirrored). Done with
      source\relabel.py (Open Sans Bold, inpainted background). KRN's
      original: backup_original\Textures\Shared_Material.png.

  Textures\Buttons.png   (v1.7)
      the top-left bezel rocker: KRN's cog and arrows -> "PWR" + power
      symbol (the texture is mirrored left-right on the model, so the text
      is drawn mirrored). Done with source\repaint_pwr.py. KRN's
      original: backup_original\Textures\Buttons.png.

  Shapes\UFCP.edm
      18 click-box connectors added to KRN's model: see section 4.

  Options\options.dlg, Options\optionsDb.lua
      4 checkboxes added (mig29dl_datalink, mig29dl_rwr, mig29dl_launch,
      mig29dl_map). KRN's own "f16c_enabled" box must stay - it is the
      switch that enables the whole KRN cockpit for the MiG-29.

  Cockpit\Textures\IndicationTextures\
      added: mig29_dl_font.dds (page font), mig29_dl_logo.dds (squad badge)

  Cockpit\Scripts\DL\     whole folder is ours (section 2)

Quick check after re-applying: compare each file with the same file in
backup_original - the only differences should be the lines above.


2. OUR FILES
------------
Cockpit\Scripts\DL\
  dl_config.lua     all settings (DL_CFG) + reads the 4 Special options at
                    the end. Users may edit this file.
  dl_device.lua     the cockpit device: UDP receiver, buttons, SA page logic
  dl_page.lua       SA page elements (indicator) + shared drawing helpers
                    (DLH table), then loads dl_pages.lua
  dl_pages.lua      elements of all other pages (MENU, PLAN, HSI, COM/NAV,
                    FPAS, SMS, FLT, RWR), alert banners, brightness layer
  dl_pages_dev.lua  logic of those pages (DL_PAGES module, used by dl_device)
  dl_plan.lua       flight plans: mission route, .dtc cartridges
  dl_theatres.lua   map detection (terrain.convertMetersToLatLon checkpoints)
                    + loads charts\<map>.lua
  dl_textures.lua   registers the logo and, if the moving map is on, the DCS
                    chart tiles of the current map as textures
  dl_fonts.lua, dl_font_desc.lua   the texture font (16x16 grid, square)
  dl_ufcp.lua       one text line on KRN's UFCP display
  dl_ewr.lua        v1.7.8 EWR picture from server text (DL_EWR module)
  dl_tac.lua        PICTURE grouping and INTC intercept steering (DL_TAC module,
                    used by dl_device, dl_pages_dev and dl_page)
  dl_geo.lua        geo drawings: reads DTC\<cartridge>.geo.txt, draws it on
                    the SA page (DL_GEO module, used by dl_device and dl_page)
  dl_boot.lua       (v1.7) display power + start-up screens (DL_BOOT module,
                    used by dl_device: tick from update, command from SetCommand)
  dl_boot_page.lua  (v1.7) elements of the start-up screens and the dark mask
                    (loaded from dl_pages.lua after all pages, before the alerts)
  dl_debug.lua      tiny log helper (Logs\mig29dl_<name>.log, max 300 lines)
  charts\<map>.lua  generated index of DCS's raster chart tiles (section 5)

Scripts\MiG29DL_Export.lua   (runs in the export environment)
  Only active while the player sits in a MiG-29. Builds the datalink
  picture from LoGetWorldObjects (needs the server to allow object export),
  reads jet data (engine, payload, snares, route, cockpit knobs) and the
  SPO-15 lamps, sends it all to the cockpit over UDP. Reads the Special
  options from Config\options.lua.
  Hooked in by one line at the end of Scripts\Export.lua (INSTALL.bat adds
  it, UNINSTALL.bat removes it).

Scripts\Hooks\MiG29DL_Hook.lua   (runs in the game GUI environment)
  Bullseye, map name, the DTC stored with the jet in the mission, the
  mission radio presets, which player flies which slot. Does nothing on a
  dedicated server or for spectators. The live player list comes from
  net.dostring_in("mission") - only possible in single player or when
  hosting from your own PC.


3. HOW THE PARTS TALK
---------------------
UDP to 127.0.0.1:42888 (the cockpit device listens). Packets are text,
first line is the packet name:
  MIG29DL   (export, 1/s)   S status  O coalition  N nav panel  X knobs
            Q systems  E engines  L radar lock  G ground threats
            C contacts  F friendly aircraft  Y stores  Z gun/chaff/flare
            W/A route
  MIG29DLV  (export)        P = SPO-15 lamps (full-fidelity jet, sent on
            change + every 0.5 s) or V = LoGetTWSInfo emitters (FC3 jets)
  MIG29DLB  (hook, 5 s)     bullseye
  MIG29DLR  (hook, 5 s)     map, mission DTC route, radio presets
  MIG29DLW / MIG29DLM (hook, 10 s)  player names by unit
  MIG29DLE  (hook, v1.7.8)  a server's "EWR ... Picture Report" trigger
            text as shown (onTriggerMessage), ASCII; dl_ewr.lua parses
            it (TYPE BRG RNG NM ALT ft SPD Knts HDG ...) into contacts
            code 1 / 2 placed from the jet's position on arrival

Cockpit parameters: DL_* = SA page, DLP_* = the other pages.
DL_MODE (page): 0 MENU, 1 SA, 4 FPAS, 5 COM/NAV, 6 cartridge list (the
old PLAN page; its route view is now part of NAV), 8 HSI, 9 FLT, 10 RWR,
11 SMS, 12 NAV, 13 RTE, 14 PICTURE, 15 EDIT (v1.7.3 route editor), 16 SNAKE (v1.7.4 easter egg),
17 LOFT (v1.8.4, dl_loft.lua)
(2, 3, 7 are free - old pages).

Button commands (device devices.MFCD):
  1101-1105 left column 1-5 (KRN's MFD-1..5), 1108 bottom centre (MFD-8)
  1106 1107 1109 1110  bottom B1 B2 B4 B5
  1111-1115  right R1-R5      1116-1120  top T1-T5
  1121/1122 brightness  1123/1124 day/night  1125/1126 SYM
  UFCP keypad: 6000 + KRN UFCP button number (16-27), see dl_config
  UFCP STP switch: KRN's 6028 (up) / 6029 (down) - we listen as well;
    only used while a cartridge is loaded (in MSN KRN steps its own route)
  UFCP MRK 6041, DIR 6043, NAV 6042 (clickabledata); KRN's own 6011 /
    6012 / 6015 are accepted too (key bindings) - dl_config ufcp_*_cmd
  NAV panel WP-A/D buttons 1-3: press animation args 424 / 425 / 426
    (a press counts as the newest input even on an already lit button)
  Keypad entries (M.entry in dl_pages_dev): HDG/CRS/TCN 3 digits, BNG 4,
  TOT 6 (HHMMSS; HHMM + ENT also accepted).

NAV page and steerpoint selection (v1.4):
  * Plans (dl_plan make): pts = route points first (pts[1..nrt]), then
    the airfields. Route = the cartridge's Route (any length; DCS's own
    DTC editor allows it), else its Waypoints; names = the point notes.
  * Selection PL.src: "nav" (NAV panel lamps / buttons), "krn" (KRN STP
    index, MSN only), "stp" (our index PL.stp_i: STP switch with a
    cartridge, NAV PREV / NEXT, auto-sequencing, typed-in points). The
    newest input wins. PL.act = the selected point, PL.cur = plan in use.
  * Leg (PL.leg_start): from the previous route point; for the first
    point, after DIR (PL.dir_i) or for airfields / NAV panel points from
    where the jet was when it was selected. XTK + = right of the leg.
    Command track = DTK - clamp(XTK / 5 km x 45, +-45 deg).
  * Auto sequencing (PL.seq): next route point within 3 km
    (nav_seq_radius_m) or passed abeam within 10 km (nav_seq_abeam_m).
  * v1.7.3 working route (replaces v1.7.1's PL.user / PL.merge): update
    runs plan = PL.route_of(base) = base -> apply_rte -> a COPY of the
    route points (PL.work = {key, view, list, plan}). Every edit changes
    only PL.work.list (edit_route in dl_device): PL.add_user (NAV ADD,
    after the active point, then DIR), PL.del_user (NAV DEL = the active
    steerpoint, any route point), PL.wp_insert / wp_delete / wp_move /
    wp_set (EDIT page). edit_route keeps the active steerpoint on the same
    point TABLE (identity); deleted -> the next one. PL.work.key = plan
    name + PL.wgen + rte_sig + every point's x/z, so the MSN plan (a new
    table every export packet) keeps its edits; PL.reset_work() (LOAD,
    slot change, set_rte with a new choice, dtc_route) starts again. The
    .dtc file is never written. stp_step uses PL.cur (v1.7.1 used PL.plan
    = the cartridge as loaded: NEXT never reached typed points and stayed
    on point 1 with a one-point cartridge). TOTs (M.tots by route index),
    the TOT cursor and the EDIT cursor (M.ed_i / M.ed_w) follow their
    points via follow_points(C, snapshot) in dl_pages_dev after each edit;
    plan.nrt_base / rte_sig stay fixed through edits, so tot_key holds.
    EDIT page (mode 15, DLP_WED_*): own cursor (right 1-5), PREV/NEXT page,
    MV UP/DN, POS, ADD, DEL x2,
    STP, DONE; coordinate entries carry M.entry_for = NAV / EDADD / POS.
    Entry M.entry "LL" (13 digits) / "MGRS" (2-10 digits in the jet's own
    100 km square); UTM / MGRS maths in dl_plan (checked against pyproj),
    lat/long <-> x/z with require("terrain").convertLatLonToMeters /
    convertMetersToLatLon.
  * Route picking (RTE page 13, PL.rte / PL.apply_rte / PL.set_rte,
    DL_PLAN.route_view): PL.rte = route indices of the full plan (PL.base)
    in flying order, nil = whole route. Member tags = digits + space at the
    start of a point note ("12 TGT"), parsed in dl_plan pts_of (w.tags);
    DL_PLAN.members lists them, DL_PLAN.all_order = every point once by
    point number (used as ALL when a plan has tags). Plan chain in update:
    base -> apply_rte -> working route copy (PL.route_of). TOT key includes
    plan.rte_sig, so TOTs reset when the route changes (not on edits).
  * DL_MAX_WPTS (dl_config) = 40 SA page point slots (page + device).
  * Sub-page side labels (dl_pages.lua): smaller font (sub_btn_label_scale
    0.8) and per-row offsets sub_btn_dy_left / _right measured on
    screenshots of the cockpit (5 values each, + = up).
  * UFCP (dl_ufcp.lua): with a cartridge (or our STP selection) KRN's
    steerpoint line and the line under it are covered (black patches,
    8 characters a line): "STP P3" / bearing (magnetic, via KRN's
    MM_AC_HDG_MAG) + distance.
  * RSBN view (R5): cartridge RSBN 1-3, then the nearest map stations
    (Beacons.lua); NO RX beyond 4.12 x (sqrt(h) + sqrt(10)) km, max 380 km.
  * Params DLP_NAV_* (SRC STP BRG TIME LEG CMD STEER SV AUTO SEQ ADD
    VIEW RSEL L1-5 C1-5 T1-5 R1-4 RC1-4).

Time on target (NAV page, dl_pages_dev tot_calc / upd_tot; along the route points):
  * left 3 PT moves the cursor M.tot_pt, left 2 TOT sets the time for it,
    left 4 CLR removes it. State: M.tots[route index] = seconds of day
    (any number of points).
  * Legs: the TOTs ahead split the route; each leg's speed = distance
    since the previous TOT (or the jet) / time since it. Planned ETAs use
    those speeds, after the last TOT the current ground speed. A TOT that
    has passed or is not after the previous one marks its leg (and all
    later ones) "CANNOT MAKE". The cue / early-late works on the first TOT
    ahead; the THEN line shows the second.
  * Clock = get_absolute_model_time() % 86400 (mission time of day).
  * Ground speed from the jet's own position over the last ~4 s
    (M.gs_hist), restarted when the page was closed. Only computed while
    PLAN is open.
  * Route: the selected steerpoint (C.act) is "next"; earlier points are
    flown (grey). Distances are own position -> next, then point to point.
  * Fuel = total fuel - measured flow (FPAS sampler) x time. Fuel at the TOT
    point uses the time left to the TOT; after it, the current ground speed.
  * Params DLP_TOT_* (ON, HINT, L1, ST, C 1-3 colour, SPD, THEN, RX/RV
    box, GX/GV caret, FUEL, FC), DLP_FPL_T<i> on a row: 1 TOT tag,
    2 PT cursor, 3 both. 10 rows.
  * Settings (dl_config, optional): tot_on_time_s (5), tot_max_kmh (1500).

Geo drawings (v1.5, dl_geo.lua):
  * Sidecar file next to a cartridge: Saved Games\DCS\DTC\<file name>.geo.txt
    (same name as the .dtc file, not the name inside it). Written by the
    Vitezovi DTC Planner (DRAWINGS tab); its parser (parseGeo in the
    planner) and DL_GEO.parse must accept the same lines:
      RING / RING? <name> <radius km> <lat> <lon>
      FLOT / BORDER / AREA <name> <lat lon> / <lat lon> ...
    "#" comment, name = words before the first number, UTF-8 BOM and CRLF ok.
    Bad lines are skipped and listed in mig29dl_device.log.
  * Loaded when the cartridge becomes PL.plan (DL_GEO.load, cached by name),
    lat/long -> x/z once with terrain.convertLatLonToMeters.
  * Drawn every SA update in the dl_own frame like the threat rings: the
    device clips each edge to geo_clip and cuts the dash pattern itself,
    then writes the pieces into fixed pools of line objects per colour
    (DL_GEO_<pool><i>_X1/Y1/X2/Y2/V, pools in dl_config DL_GEO_POOLS) and
    up to DL_GEO_LABELS labels (DL_GEO_L<i>_X/Y/T/C, C 1 red 2 pink 3 cyan
    4 grey). Unused pieces are switched off. A full pool just drops the rest.
  * SA right 1 GEO (DL_GEO_BTN 0 none / 1 shown / 2 hidden) toggles only
    these; datalink threats (export) are separate. SYM 4 hides the labels,
    SYM 5 the drawings. Elements sit before the scope in dl_page, so the
    route, threats and contacts draw on top.
  * update() calls DL_GEO.draw(view) with view.oy / sym / unit_m / unit_lbl
    set just before - no new locals in update (upvalue budget, see below).

PICTURE and INTC (v1.6, dl_tac.lua) - advisory only, nothing goes back to
the jet (autopilot, HUD, radar, weapons stay stock):
  * Export: contact lines may carry a 9th field, the aircraft type: C,typ,x,z,y,vx,vz,age,F-16C_50. Older cockpits ignore
    it; the cockpit reads it as c.nm (DL_TAC.short_type -> "F-16").
  * DL_TAC.groups: hostiles (type code % 10 == 2) linked into groups when
    within pic_group_m (9300 m) and pic_group_alt_m (3000 m) of another
    member (single linkage). Group = centroid, highest altitude, mean
    velocity, most common type. Aspect from the group's track vs the line
    to the jet: HOT <= 30 deg, FLANK <= 70, BEAM < 110, DRAG.
  * PICTURE page (DL_MODE 14, SA right 2): upd_pic in dl_pages_dev, 5 rows
    by range (DLP_PIC_R<k>, colour C<k> 1 red / 2 green, selected box S<k>),
    call lines K1-2, north-up plot with groups G<k>_X/Y/H/V (V 1/2 hostile,
    3/4 friendly, even = selected) and the jet OX/OY/OH. Bottom 1/2 plot
    range steps 25-400 (M.pic_scale, nil = AUTO, bottom 4), bottom 5 SHOW
    HOSTILE / FRIENDLY / ALL (DL_TAC.groups side "H" / "F"; friendly = type
    codes 1 4 5 6). Left 2 CALL BULL / BRAA (also the plot centre: bullseye / jet), 4 INTC (start on the group, back to SA),
    5 SA (cursor on the group via CX.cursor_to). Right 1-5 pick a group;
    the pick is kept by position while the list re-sorts.
  * INTC (SA right 3): DL_TAC.intc_start picks the contact nearest the
    cursor (else the nearest hostile; from PICTURE the group). Each SA
    update DL_TAC.draw follows it (nearest contact to the predicted spot,
    gate intc_gate_m), solves the collision course with the jet's TAS
    (min intc_min_speed 150 m/s): |D + Vt t| = Vo t. No solution = target
    too fast / opening: pure pursuit, "TAIL CHASE". LOST after intc_lost_s
    (12 s) without a matching contact, dropped after 60 s.
    Params DL_INTC_*: ON, TX/TY/TV target ring, XX/XY/XV meeting point,
    pools y (jet -> X) / r (target -> X) of dashes, heading bar DX/DP
    diamond (only with DL_INTC_ON), T1-T4 readouts (bottom right, the
    cursor datablock DL_HOV_* is off meanwhile; dark backing panel over the
    map), C4 fuel colour.
    v1.8.1 heading tape (F/A-18 style) = DL_TAC.tape(hd, diff) in dl_tac:
    +-25 deg, K1-11 ticks every 5 deg (_V 1 short / 2 long), N1-6 numbers
    above the long ones (heading/10, "%02.0f" by the element, 0 -> 36),
    DL_HDG_T boxed heading ("%03.0f"), DL_HDG_ON visibility (device:
    SA page, SYM < 5, CFG.hdg_tape ~= false, or an intercept). Writes only
    changed values. Tape at hdg_tape_y 1.13, hdg_tape_scale 0.0165 page
    units/deg, hdg_tape_size 1.1 (numbers, ticks, box, diamond). SA header
    (layout 3): range scale right and own bullseye "BE 136/47" left, just under
    the H1-H5 labels beside the tape numbers (hdr_corner_x 0.88, hdr_corner_y 1.26;
    above the H row the rounded screen cuts text off in DCS; range
    hdr_range_scale 0.8, BE hdr_be_scale 0.85); steerpoint "W2 038/28" and
    the status line right at hdr_y 1.02 / -0.10. Units are only on the range
    scale: be_of(be, x, z, true) drops the unit when bullseye_units is the
    range unit (cursor / hover BE readouts keep it). text_top_y unchanged
    (label limits use it). The tape is built by hdg_tape(PRE, PAR, y) in dl_page
    (DLH.hdg_tape): SA = "dl_intc" under dl_root, RWR = "dlp_rwr_hdg" under
    dlp_rwr, same DL_INTC_K/N/DL_HDG_* params; on page 10 the device sets
    DL_HDG_ON and calls DL_TAC.tape (rwr_hdg_tape = false: off). RWR ring
    compass: dlp_rwr_rot (DLP_RWC_ROT = heading) + upright labels
    DLP_RWC_L0-11_X/Y at rwr_radius + rwr_label_dr (0.17), set in upd_rwr;
    RWR title at rwr_top_y 1.37 (screen is cut above ~1.49 and left of ~-1.0 in DCS), no DLP_RWR_STAT element any more, DLP_RWR_CM bottom right at rwr_cm_x 0.92 / YB, rwr_radius 0.62 / rwr_center_y 0.10
    (dl_config), list from rwr_list_y -0.76, 0.072 apart. Test: devtools/t_tape.py. The DTC and source header lines are blanked meanwhile.
  * SA header (v1.6): DL_OWN_BE top left, range + DL_STEER_TXT right,
    DL_STATUS_TXT (amber) only for NO DL / DL OFF. DL_HDG_TXT, DL_SOURCE_TXT
    and DL_DTC_TXT are still set by the device but no longer drawn.
  * Export: ejected pilots / parachutes (Name "pilot..." / "parachut...")
    are skipped; contact lines carry the type for every contact.
  * Steering (v1.6): PL.steer_to(point, ox, oz) in dl_device is the ONLY
    bearing / distance to the active steerpoint; SA "TO ..", UFCP line 2
    (DL_UFCP_BRG, element format "%03.0fT"), NAV (nav.steer_to) and HSI text
    use it. All true north. Do NOT use KRN's MM_AC_HDG_MAG as a magnetic
    heading - in flight it was 150 deg away from the real one.
    NAV route list BRG / DIST are from the jet (direct), ETA along the route.
  * SA side labels: TXT_BTN x sa_btn_label_scale (0.75); sub pages
    sub_btn_label_scale 0.72.
  * Button label positions (dl_config btn_label_y / _right, btn_row_x /
    _bottom) were re-measured on in-cockpit screenshots of every page in
    v1.6: label centre on the button's centre line. The old per-row nudges
    (sub_btn_dy_left / _right) are 0 now. To re-measure: screenshot the MFD
    straight on, take the button bars' and the label lines' pixel rows; the
    distance from left button 1 to 5 is 1.76 page units (the scope diameter
    at 0.88 radius gives the same scale). The bottom MENU label sits on
    button 3 (ROW[3]), not at x = 0.
    Fuel at X = fuel - measured flow (DL_PAGES.ff) x time; vs DL_PAGES.bingo.

Full-fidelity MiG-29 facts we depend on:
  * LoGetTWSInfo is nil -> the RWR reads the SPO-15 lamps (cockpit
    arguments, from the module's Cockpit\Scripts\ASE\L006LM\lamps.lua):
      sectors 191-198 (L70 L50 L30 L10 R10 R30 R50 R70), 199/200 rear
      main-threat sectors 150-157, 158/159 rear
      type lamps 171-176, main type 164-169 (P Z H N F S)
      lock 162, above 160, below 161, power 202-216, SPO on 177
    A flashing lock lamp is treated as a launch. If ED renumbers these,
    the RWR page goes blank: check that lamps.lua again.
    Which rear lamp is left/right is a guess: dl_config rwr_swap_rear.
  * Radio: R-862 is device 51. set_frequency is ignored by the jet, so
    frequencies can only be shown, not changed.
  * LoGetPayloadInfo works; CurrentStation stays 0 (no "selected" station).
  * Engine temperature from LoGetEngineInfo is wrong (negative), EGT comes
    from the cockpit sensor data instead.

Rules that bit us (keep them):
  * Never put a number-only string into a text parameter ("80", "7") -
    DCS stores it as a number and the text format crashes. Use the T()
    helper in dl_pages_dev, or add a letter.
  * Lua 5.1: one function may use at most 60 outside locals. update() in
    dl_device.lua is close to it (56 used in v1.7.2, 4 to spare).
    Check with a real Lua 5.1 compile (lupa.lua51), not LuaJIT. Put new state in existing
    tables (H, view, DL_PAGES) instead of new locals.
  * Text from users or maps (cartridge / point / beacon / unit names)
    goes through DL_ascii / DL_text (dl_config.lua) or DL_PAGES.ascii:
    the MFD font has ASCII 32-126 only, and DL_text also keeps a string
    from ever looking like a number.
  * Theatre names: missions, the hook's T line and .dtc files use DCS's
    theatre id (GermanyCW, SinaiMap, MarianaIslandsWWII ...); terrain
    folders and chart files the folder name (GermanyColdWar, Sinai,
    MarianasWWII). Always go through DL_theatre_id / DL_theatre_folder /
    DL_same_theatre (dl_theatres.lua, loaded on device and display side).
  * DL_GEO.draw / DL_TAC.draw protect themselves (pcall, log once, hide)
    so an error cannot stop update(); keep new per-frame code that way.
  * Move controllers need gain G = 0.045 (see dl_page.lua).
  * The texture font must stay square with a square grid.
  * Parameter handles are cached and only written when the value changes
    (the P() helper) - keep it that way for performance.


SRS radios 2 / 3 (v1.8.5, dl_srs.lua, COM/NAV page 5):
  * SRS's MiG-29 export (DCS-SRS-Modules/Mig29Fulcrum.lua): radio 1 = R-862
    (cockpit device 51, SRS reads it; we never send to it), radio 2 =
    AN/ARC-186 VHF 116-151.975, radio 3 = AN/ARC-164 UHF 225-399.975, both
    expansion radios with freqMode / volMode 1 (overlay controlled), so
    SRS takes UDP commands for them (port CFG.srs_port 9040):
    {"RadioId":r,"Frequency":MHz,"Command":12} and {"RadioId":r,"Volume":0..1,"Command":5}
    (same messages as the F-15C SIT add-on 1.2 sit_device.lua srs_set / srs_vol).
  * DL_SRS keeps channel / volume / 20 presets per radio, file
    Vitezovi-MFD-Addon\srs_radios.txt (written on every change), defaults
    CFG.srs_vhf_presets / srs_uhf_presets. dl_device hands it a sender on
    its own socket (DL_SRS.init, module level) and calls DL_SRS.tick in
    net_tick (not in update(): upvalue budget); first send 3 s after start.
  * Page: DLP_RDO_SEL 1/2/3 (top 1-3), DLP_RDO_VHF/UHF lines, src line and
    DLP_RDO_MSG (EDIT entry "RDO" on the keypad, DL_SRS.parse) share
    y 0.86 via DLP_RDO_MSGON. Binds 1130-1137 (vitezovi_binds.lua) are
    handled first in SetCommand (before DL_BOOT.command: work with the MFD off).
  * Test: devtools/t_srs.py; preview project files srs/preview_comnav.py.

LOFT page (v1.8.4, dl_loft.lua, page 17, MENU right 5):
  * DL_LOFT (device side, loaded by dl_device with pcall) -> DL_PAGES
    calls DL_LOFT.update(C) on page 17 and gives it every button there
    (DL_PAGES.command, after M8). Elements in dl_pages.lua root "dlp_lft",
    params DLP_LFT_*; geometry numbers are written twice (dl_loft.lua and
    dl_pages.lua, different Lua states) - keep them in step.
  * Weapon: DL_PAGES.sel_store(C) = the store on the selected stations
    (sms_select, the SMS page logic), DL_LOFT.weapon_of(name) maps the
    export's store name to L.W (OFAB before FAB, BetAB-500ShP and KMGU
    excluded). WPN (left 3) overrides.
  * DL_LOFT.fly(w, v, gam, h0, hend, pts): point mass, ISA, midpoint steps
    0.05 s while the motor burns, then 0.25 s. Rockets: thrust along the
    velocity, launch angle = flight path angle. Drag ref area pi d^2/4:
    S-8 = DCS Cx0 table x k 0.985, S-24B = Mach table measured from
    Tacview x k 0.92, bombs constant cd (FAB-500 0.14 measured, rest est).
    Checked against 40 S-8, 2 S-24B, 4 FAB-500 Tacview shots (15 Nov 2026,
    DCS 2.9.31): within 0.8 % (S-8), 0.5 % (S-24B), 1-3 % (FAB-500).
    Research and scripts: project files loft/ (not shipped).
  * Release angle solution once a second (plus level and max range at
    30/38/45 deg), "fired now" 10 times a second. Pull = a steady
    loft_pull_g (4 g) pull, rate (n - cos fpa) g / V (loft_pull_dps
    forces a fixed rate); pull_of(a) gives its time, ground covered and
    height gained - the plan releases that much higher, the pull point =
    release range + ground covered. SHOOT window: weapons with w.win
    (bombs, S-24B) +-50 m; others loft_early_m (60 m, 0.6 %) short to
    loft_tol_m (150 m, 1.5 %) long. SHOOT also comes up one update early
    when the next solution would jump past the window by more than this
    one is short (fast pulls), and when a new solution jumped from short
    straight to long; it stays up at least 0.4 s.
  * IN RNG (cue kind 5): weapons with w.ir (S-8 pods, RBK; 500 m,
    loft_inrng_m overrides) while holding the angle and a shot fired now
    lands within w.ir short. Range bar band IB0/IB1 above OPT, profile
    ground band GB0 -> TX.
  * Range bar (left, x GEO.rbar_x -0.60): MIN = level shot, OPT = pull
    start, MAX = 45 deg + its pull; scale = next round value (NICE);
    MIN/MAX labels hide within 0.07 of OPT. Pitch ladder: lines every
    5 deg, K 0.024 page units per deg, each shown inside +-0.21 of the
    jet symbol; release angle line LRY (clamped to the window).
  * Velocity from sensor data getSelfVelocity, else position
    differences. Target height terrain.GetHeight, else 0.
  * Heading tape on page 17 = the shared one (device sets DL_HDG_ON as on
    RWR); the steerpoint diamond is the page's own (DLP_LFT_DX/DV).
  * Test: devtools/t_loft.py [S-8KOM|S-24B|FAB-500M-62|RBK-250] [angle]
    (T_PULL_G pull g, T_REACT seconds from SHOOT to fire).

3b. DISPLAY POWER AND START-UP (v1.7, dl_boot.lua / dl_boot_page.lua)
----------------------------------------------------------------------
  * POWER = KRN's cog rocker, top of the left column (bone node 30,
    animation arg 101). Click box MFD-PWR (patch_edm.py), clickabledata
    element MFD-PWR (device = our MIG29_DL) sends 1127 on press and on
    release. Press with power = start-up; hold power_hold_s (2 s) = off.
    The hold is timed in DL_BOOT.tick (DL_PWR_HOLD 1..10 = the bar).
  * RELEASE VALUES (tested in the cockpit, v1.7): a press arrives as 1
    (or -1), the release of the same button as 0.25 - NOT 0. DL_BOOT.command
    treats |value| < 0.5 as a release and drops it for every bezel command
    1101-1127 on every page, and drops a repeat of the same bezel button
    within button_debounce_s. Before this, releases counted as presses
    (POWER switched back on, DOWN stepped twice, MSN fell through to FPAS).
    Reading arg 101 from the device returns 0 even while the rocker is
    pressed - it cannot be used to see the button.
  * v1.7.1: on other PCs POWER arrives with large values (517.375 press,
    517.25 release seen in a squad mate's log), so |value| < 0.5 alone
    misses the release. POWER now also counts as a release: a value
    already seen as a release (B.rel_v), or any value other than the
    open press's value (B.press_v). A hold-off keeps the press open
    (B.hold_done) until its release, so the release cannot switch the
    display on again. The hold only switches off once a release has been
    seen (B.rel_seen) - a setup that never sends one keeps the display on.
    mig29dl_device.log shows each POWER value and how it was read.
  * v1.7.2: ONE press/release tracker per command for every button we
    handle (bezel, keypad, UFCP keys, STP switch) in dl_boot.lua.
    Commands whose clickable sends a release (table RELEASING in
    dl_device.lua: B1..T5 1106-1120, KRN's MFD-3/4/5/8 1103-1105/1108,
    POWER 1127 - keep it in step with clickabledata.lua): release =
    |value| < 0.5, a value learned as that command's release, or any value
    other than the open press's; a repeat of the press value within 0.3 s
    of the PRESS is dropped; two presses < 0.1 s apart count once; an open
    press expires. Every other command is press-only (KRN's keypad, UFCP
    keys, MFD-1/2, rockers, STP switch: no release message): |value| >= 0.5
    = press, a press within button_bounce_s (0.15 s) of the last accepted
    one is dropped. button_debounce_s is no longer used. POWER: the bar fills while held, at full it reads
    "RELEASE TO SWITCH OFF" and the RELEASE switches off (a lost release
    can never switch off). The 14 added bezel buttons (B1..T5) now go to
    our own device (devices.MIG29_DL) as press + release and animate;
    KRN's MFD-3/4/5/8 are redefined with the right args.
  * v1.7.2: a power cut from power_blink_s (1.5 s) to power_keep_plan_s
    (30 s) replays the start-up but skips the cartridge choice when a plan
    was loaded (plan, typed points and steerpoint stay); a longer cut (a
    real shutdown, rearm) restarts completely incl. the cartridge choice.
    INTC is stopped when the display goes off.
    An error in the start-up code switches to the pages ("on") so the
    buttons keep working. While off / starting, DL_UFCP_NAV and
    DL_UFCP_MENU are 0 (KRN's UFCP shows).
  * Shared layout constants of dl_boot.lua and dl_boot_page.lua are
    DL_BOOT_CONST in dl_config.lua (the display state has no DL_BOOT).
  * Jet power: BAT / GROUND switch arg 510 and voltmeter arg 308 (0..1 =
    0..30 V) of the full-fidelity MiG-29 (Mods\aircraft\MiG-29-Fulcrum\
    Cockpit\Scripts\clickabledata.lua / mainpanel_init.lua). Once the
    meter has moved: >= power_min_volt with the switch on, or >= 26.5 V
    (generator) without it. A meter that never moves: the switch alone.
    The first frame and every change are logged in mig29dl_device.log.
  * States (DL_BOOT.state): nil (first boot_spawn_s seconds: powered =
    hot / air start -> "on"), "off", "boot", "on". DL_BOOT.sw = the POWER
    latch: a cut longer than power_blink_s -> "off", and with sw still on
    the start-up runs again when power returns. Shorter gaps only darken.
  * DL_BOOT param (one root per value in dl_boot_page.lua, each with a
    full black background, drawn over every page and KRN's page):
      0 pages  1 dark  2 flash  3 test grid  4 boot ROM  5 boot log
      6 badge  7 BIT  8 cartridge choice
    Timeline in dl_boot.lua (B.TIMES): flash 0, grid 0.16, ROM 1.21,
    log ~4.5, badge ~7.9 (badge_s 4), BIT ~11.9 (11 lines x 0.26 s +
    0.9 s), cartridge choice ~15.6 s until a button.
  * Texts: boot ROM rows DL_BR_A (dim) / B (white, led by spaces so it
    follows A in the monospaced font) / W (white line), cursor
    DL_BR_CUR; boot log rows DL_BC_A (dim) / B (white, right-aligned on
    column 36) / C (white after the clock) / W, cursor DL_BC_CUR.
    Badge DL_BS_VER / DL_BS_PROG (0..20). BIT DL_BIT_S<i> (1 wait, 2 in
    test, 3 GO, 4 NO-GO), DL_BIT_I<i> (info), DL_BIT_SUM, DL_BIT_DONE;
    the line names are DL_BIT_ROWS in dl_config (same order as
    bit_results in dl_boot.lua). NO-GO: no position, no datalink packets,
    no bullseye. Version: DL_VERSION in dl_config (the only place).
  * Cartridge choice: DL_BD_* (cards N/I/V 1-4, MORE, EMPTY, ALIGN,
    preview pools RS (route, 40) RP (points, 40) GS (drawings, 60) in
    page units inside DL_BOOT.PV, PN/P1/P2, details D1-D4, LOAD). Uses
    CX.dtc_opts / dtc_load (the NAV page's LOAD) and CX.dtc_route (a
    member's points, as the RTE page does). DL_GEO.parse reads the
    .geo.txt for the preview without touching the SA page drawings.
  * While not "on": update() returns right after DL_BOOT.tick (the pages
    are not computed), SetCommand gives every MFD / keypad command to
    DL_BOOT.command (the STP switch excepted). The alerts root also needs
    DL_BOOT = 0.
  * dl_config: power_mode ("jet" / "always"), power_hold_s, power_blink_s,
    power_min_volt, boot_spawn_s, boot_skip.
  * Fonts: DL_F_DIM (dl_fonts.lua, F.dim in dl_page.lua) for the log text.

4. THE BUTTON CLICK BOXES (Shapes\UFCP.edm)
-------------------------------------------
KRN's model only has click boxes for MFD-1..5 and MFD-8. source\patch_edm.py
adds 18 more (B1 B2 B4 B5, R1-R5, T1-T5, BRT, DN, SYM, PWR), each parented to
its button's bone so the button animates:
    python patch_edm.py <KRN original UFCP.edm> <output UFCP.edm>
The original is in backup_original\Shapes\UFCP.edm.
The script checks KRN's model layout (162 nodes, 55 connectors, fixed byte
offsets). If KRN changes the model it will stop with an error - the offsets
and the bone numbers (listed in the script) then have to be found again.
Bone node k is named "Bone.(k-2)"; bone-local +y points down the bezel.
Animation args of the bezel (from the bones' positions, v1.7):
  left column top->bottom   101 rocker (POWER), 102-106 buttons 1-5, 107 SYM
  right column top->bottom  119 BRT, 118-114 buttons 1-5, 113 D/N
  bottom row left->right    108 109 110 (MFD-8) 111 112;  top row 124-120


5. MOVING MAP CHARTS (charts\<map>.lua)
---------------------------------------
Each file lists DCS's own raster chart tiles for one map (texture name,
world bounds, scale), so the page can show the tiles around the jet.
Nothing is copied - the textures are read from the DCS install.
Regenerate when ED reworks a map's charts or for a new map (needs Python):
  1. parse_sup5.py   reads Mods\terrains\<map>\RasterCharts\rasterCharts.sup5
                     of every map -> tiles.json
  2. plan.py         (used by gen_lua.py) picks the chart scale per range
  3. checkpoints.py  map detection points -> checkpoints.json
                     (needs the pydcs and pyproj packages)
  4. gen_lua.py      writes charts\<map>.lua
For a new map also add its checkpoint to DL_THEATRES in dl_theatres.lua.
The folder paths inside the scripts point to where they were first run -
edit them to your DCS install before running.
Maps without a chart file simply show no map.


5b. LOAD / LOG BUDGET (keep it this way)
  * Cockpit device: 20 updates/s only on SA and HSI, other pages 4/s;
    nothing when the MFD page is off.
  * Export: picture 1/s (LoGetWorldObjects - the biggest cost; the
    Datalink option off skips it), RWR lamps 10/s, sensor refreshes
    2-6 s with a terrain-sample budget. Tables are reused / pruned.
  * Hook: reads the mission only once somebody flies on this PC; on a
    dedicated server it only checks every 5 s and does nothing else.
  * Logs: own files only (mig29dl_*.log, rewritten each session, the
    previous one kept as mig29dl_*.old.log; device log 250 normal lines +
    50 reserved for errors); dcs.log gets at most 5 export errors a mission.
  * Export (v1.7.2): only for "MiG-29 Fulcrum"; the AWACS / fighter /
    threat refreshes run on different ticks with one LOS budget per tick;
    every packet <= 7500 bytes (names cut to 24 characters as "start~end",
    lines in priority order); unborn / static objects skipped; each
    LoGet* call protected. It runs inside other tools' export chain: our
    part in a pcall, the previous tool's function outside it, re-attached
    only when we were not called while model time advanced.
  * Hook (v1.7.2): the mission is read once per mission and only for a
    MiG-29 Fulcrum slot; the cartridge / presets are the player's own
    unit (P line = unit name), rebuilt when the slot changes; state is
    reset at every simulation start / stop; M lists occupied slots only.
  * UDP port 42888: bind without reuseaddr first; if busy, the same
    attempt binds with reuseaddr (as v1.7.1, logged "sharing it") so a
    respawn with the old socket still open recovers at once; BUSY only if
    both fail (retry every 5 s).
  * FLT members in flight.txt are compared through DL_name_cut
    (dl_config.lua) = the export's / hook's clean(): names cut to 24
    characters as "start~end". Keep the three copies identical.
  * Moving map: chart archives are mounted only with the Moving map
    option on (DCS may print "already mounted" warnings once at load).


6. TESTING A CHANGE
-------------------
  * Logs: Saved Games\DCS\Logs\mig29dl_device.log, mig29dl_export.log,
    mig29dl_hook.log, mig29dl_page.log, and dcs.log (search "MiG29DL").
    "page error (mode n)" in mig29dl_device.log = a page script failed.
  * Test missions in the package: MiG29_DL_Test_Flight.miz (4 slots,
    dynamic spawn, Kutaisi), MiG29_RWR_Test.miz (SA-6 + armed Su-27, full
    load - RWR and SMS).
  * Check: every MENU page opens, SA page with datalink, RWR lights up,
    SYM / brightness / D-N rockers, keypad entry (HSI, FPAS bingo, NAV
    TOT, ADD), one
    multiplayer session.


7. KNOWN LIMITS (not bugs)
--------------------------
  * SA / FLT need the server to allow export of world objects; without it
    only the own radar picture is shown.
  * The datalink is a simulation from the unit list (sensor ranges, radar
    horizon, terrain), not DCS Link 16 - the MiG-29 has none.
  * FPAS best range / endurance figures are estimates, not manual data.
  * Fuel and weapons of other jets are only available to the host, so FLT
    shows radar / jammer / alive status instead.
  * Radio presets can be shown but not changed in flight.
  * TOT fuel / ETA figures are estimates: no wind model; fuel per leg
    comes from a simple drag / fuel-flow model (flow_at in dl_pages_dev:
    ISA density, drag = q*wave + q_md^2/q, SFC dry 0.77 / AB 2.05, max dry
    thrust 10080 kgf scaled with density) anchored on the measured flow.
  * The HUD steering cue was tried in Nov 2026 and dropped: an extra
    collimated indicator on the HUD anchors works, but it cannot follow
    the stock HUD's own symbology (modes, tape), so it never looked right.
  * The jet's own navigation (HSI, autopilot) only knows the cartridge's
    3 waypoints / 3 airfields / 3 RSBN; the NAV page route steering is
    on the MFD and UFCP only.
  * DTC cartridges picked on the pre-spawn DTC page did not reach the jet
    on the squad's dynamic slots in our tests - load them in the jet.
  * v1.7.8 start-up hold: update() does nothing for start_hold_s (6 s,
    max 600 updates) after the device is created. Crash signature it
    targets: C0000005 in CockpitBase, ccIndicator::SetCurrentPage ->
    ccIndicatorPage::load -> ceMeshPoly/ceSimple::setValue, on a worker
    thread, right at spawn (10 + 11 Nov 2026). Theory (unproven): our
    parameter writes race the page build. Tests that act in the first
    6 s need start_hold_s = 0 in their settings.lua.
  * v1.7.8 built charts: installer\VitezoviCharts.cs (Build-Charts in
    vitezovi_install.ps1, after the file copy, never stops the install)
    reads DCS's chart zips (own zip reader, Zip64), decodes DXT1/3/5,
    resamples bilinear from the fitting mip onto a grid of 2048 px tiles
    and writes DXT1 + mips to DL\charts_gen\<theatre>\ plus the index
    DL\charts_gen\<theatre>.lua (written last; "-- sig:" line = source
    zips' size/time + ranges -> unchanged maps are not built again).
    Layers: per source class, k = coarsest 2^k with base m/px * 2^k <=
    range / 300 for every km and nm range step. DL_load_chart prefers the
    built index (DL_CFG.map_built ~= false) and DL_gen_ranges sets
    range_class = layer number per range step; tiles keep the DL_CHART
    format (t[6] = layer), so page / device / textures code is the same
    (textures get the full path chart.dir). Test: devtools inst_test.sh
    with CHARTS=<a Caucasus 5M zip>.
  * v1.7.8 export chain: check_attached re-wraps only when our wrapper is
    not reachable from LuaExportAfterNextFrame (in_chain). Before, model
    time ran during mission load without frames, RUN.ran stayed false and
    we re-wrapped every check; with a tool using the same re-attach idea
    the chain grew ~40 deep (nyuu's log 11 Nov 2026: 40 re-attaches, the
    other tool then ran 39x per frame). Test: devtools/t_load_chain.py
    (40 activity events, no frames, re-attaching tool) -> 1 call per frame.
  * v1.7.9 map dimming: DL_MAP_DIM 0..9 = nine black layers dl_mdim_<k>
    (dl_page.lua, after the charts, under all symbols; parameter_in_range
    like the DLP_DIM brightness layers - opacity_using_parameter exists in
    CockpitBase but is untried). Device: MAPDIM (dl_device.lua) - B5 steps
    map_dim_steps then OFF; MAPDIM.tick in boot_tick adds map_dim_night
    when DL_PAGES.is_night(). Toast via DL_PAGES.show_toast.
  * v1.7.9 EWR units: dl_ewr parse_line converts to metres / m/s with the
    unit tables U_RNG / U_ALT / U_SPD; unknown unit = row left out.
  * v1.7.9 installer: Build-Charts is the last step of Install-Into (after
    the Export.lua line, settings.lua and installed.txt).
  * v1.8.0 units: dl_config resolves DL_CFG.units ("auto" default) after
    the Options switches: auto reads the ED module's option
    MiG29AvionicsUnits (0 metric, 1 imperial) with get_plugin_option_value
    ("MiG-29-Fulcrum", then "MiG-29A by Eagle Dynamics") or Config\
    options.lua plugins[...]. Which id DCS really uses is not verified in
    DCS: the device log line "units: ... from ..." tells. range_units /
    alt_units / fuel_units default nil and are filled from it; DL_U.fuel /
    fuel_in / alt / spd convert for the pages (fuel kept in kg inside, M.bingo
    too). Test: devtools/t_units_mfd.py metric|imperial|auto_fn|auto_file|auto_none.
  * MAWS (missile approach warning) was tried in Nov 2026 and dropped:
    LoGetWorldObjects("ballistic") returns an empty list (even in single
    player), so export scripts never see missiles. A hook can track them
    via S_EVENT_SHOT in the mission environment, but only where the
    mission runs (single player / host) - useless for clients unless the
    squad server runs a relay. The attempt is not in the package.


8. VERSIONS
-----------
  v1.0  MENU + SA/DTC/ENG/FUEL/RADIO/FPLN/RSBN/HSI/FLT pages, squad package
  v1.1  RWR (SPO-15 lamps), SMS, markpoints, bingo/home, launch and bingo
        alerts, Special options, moving map with MAP button
  v1.2  pages merged (FPAS+ENG, PLAN+DTC, COM/NAV), menu 4+4, quick return,
        SYM declutter, EXP centring/follow, clean-up (hook idle on
        servers, own Caucasus map texture and dead code removed)
  v1.3  time on target on PLAN: ETA / fuel per steerpoint, TOTs on any
        number of steerpoints (own speed per leg), early / late, required
        speed + speed cue, THEN line, fuel at the next TOT and at the end
  v1.4  NAV page (steering bar, leg / XTK / DIR, route list, TOT, RSBN,
        auto sequencing, typed-in waypoints lat/long + MGRS, RTE route
        picking with flight-member tags, 40 SA points), cartridge
        routes of any length, UFCP steerpoint lines, STP switch for
        cartridges, NAV panel / STP / NAV page newest-input-wins, UFCP
        MRK / DIR / NAV keys (relabelled texture), fuel model per leg
        speed / altitude, smaller sub-page button labels
  v1.5  geo drawings from the cartridge's .geo.txt on the SA page (threat
        rings, suspected rings, FLOT, borders, areas), GEO button right 1,
        GCI cartridge with drawings in the package
  v1.6  PICTURE page (hostile groups, bullseye / BRAA, the call, plot),
        INTC intercept steering on the SA page, hostile types in the export
  v1.7  display power and start-up (PWR rocker, boot ROM / log / badge /
        BIT / cartridge choice), all bezel buttons animated, add-on
        package that installs on top of KRN's own download
  v1.7.1 POWER release values of other PCs (517.375 / 517.25)
  v1.7.2 full code review: one press/release tracker for every button,
        POWER off on release, settings.lua, own-slot mission cartridge,
        theatre names (Sinai / Germany CW / Marianas WWII), unborn units
        skipped, safe export chaining and packet size, NaN-proof TOT /
        INTC / PICTURE fixes, installer: KRN-update safe, registry Saved
        Games, [ ] paths, byte-exact Export.lua, clear error messages;
        DTC Planner: ASCII names, zip save, exact coordinates
  v1.7.3 working route + EDIT page (move / re-position / add / delete
        any route point, own cursor, page buttons); NEXT / STP step
        through typed-in points; the .dtc file is never written.
        Installer data: gen_patch.py (= gen_patch173.py) knows the v1.7.2
        results and dl_config.lua; KRN-file results are the same as v1.7.2.
  v1.7.4 HOTAS binds, SNAKE, TDC slew code removed (see "v1.7.4" below).
  v1.7.5 timing log (perf_log), SA scope only on SA, less garbage, export
        work spread over frames (see "v1.7.5" below).
  v1.7.7 night palette fixed (element builder), STORES selection from the
        INBD/OUTBD switch, all Options > Special switches on by default.
  v1.7.6 STORES page (rear view), SA label grouping
        (SYM 2 / 3), SA cursor square, HSI route strip (see "v1.7.6" below).


v1.7.4
------
HOTAS binds (Options > Controls > MiG-29, category "Vitezovi MFD")
  * installer\vitezovi_binds.lua = the rows (56): the SAME global commands
    the clickables send (no cockpit_device_id: KRN's devices are plugin
    devices, not in the MiG-29's own device list), with value_down /
    value_up like a click - 1 / 0 on the releasing buttons (PWR 1127,
    1103-1105, 1106-1120), press only (value 1) elsewhere, STP down 6029
    = -1 (KRN's default_switch_2_pos). ED's own MiG-29 file uses value_down
    on global commands the same way (VoIP PTT), so the values arrive.
  * vitezovi_install.ps1: Get-DcsInstalls (-DcsPath, ED registry keys,
    Steam app 223750), Set-Binds puts the block between
    "-- VITEZOVI MFD ADD-ON BINDS BEGIN" and "... END" before the LAST
    "return res" line of Input\MiG-29-Fulcrum\joystick|keyboard\default.lua
    (same line ends as the file), replaces an older block, -Uninstall
    strips it (the file is then byte for byte ED's again). The first
    install keeps ED's files in Vitezovi-MFD-Addon\dcs_input_backup.
    Never stops the install: no install found / no permission = a note.
  * dl_device.lua (at load): CX.binds = is the BEGIN marker in
    <lfs.currentdir()>/Mods/aircraft/MiG-29-Fulcrum/Input/.../joystick/
    default.lua (nil = cannot read); the BIT's UFCP LINK row shows
    HOTAS BINDS / NO HOTAS BINDS.
  * The full package's INSTALL.bat (robocopy) does not do the binds; the
    add-on package's does.
SNAKE (dl_snake.lua, DL_SNAKE)
  * opened by typing 77776625533 (S N A K E on a button phone) on the UFCP
    keypad on any page (DL_PAGES.command keypad block; any CLR / ENT
    resets the sequence); page 16 runs at 20 Hz (dl_device update).
  * every button goes to DL_SNAKE.key while on page 16: 2/4/6/8 steer,
    5 pause, ENT start / again, CLR back (M.snake_from), MFD-8 MENU.
  * body = a ring of DL_SNAKE_MAX (dl_config, 100) slots DLP_SNK_X/Y/V<i>
    (move controllers with gain G, like the cursor); a step writes only
    the new head slot and the old tail slot. Head DLP_SNK_HX/HY, food
    DLP_SNK_FX/FY (red diamond), banner DLP_SNK_BAN 0 off / 1 green /
    2 red / 3 amber. About 220 display elements.
  * best score in Saved Games\DCS\Vitezovi-MFD-Addon\snake.txt.
TDC: the cursor slew (commands 3010-3016, 3038/3039, cursor_speed &c.)
  is gone - those commands never reached the add-on in the MiG-29.


v1.7.5
------
Measured first (timing log below, one flight in the sim): every page cost
mostly the SA scope work, also where it was not shown; the export's one
big frame per packet was the only thing near a visible hitch.
SA scope only on SA (dl_device.lua)
  * update() keeps: sensors, plan / route choice, PL.seq, DL_GEO.load,
    bullseye, CX, DL_PAGES.update, UFCP lines. draw_scope(t, sd, ox, oz,
    hdg, plan, stale, be) has the rest (header texts, map tiles, compass,
    route / mark / active waypoint symbols, cursor, geo, INTC drawing,
    threats, contacts, H1-H5 / NEXT, lock, hover block) and runs only for
    DL_PAGES.mode == 1. Everything it sets is under dl_root (DL_MODE 1),
    so it is hidden on the other pages anyway.
  * off SA with an intercept running: set_view() + DL_TAC.draw() still
    run (tracking; the intercept would be dropped after intc_drop_s).
  * map tiles are updated only on SA now (they stay loaded meanwhile).
  * update() now has few upvalues; draw_scope() 51 (limit 60).
Garbage
  * constant tables CONTACT_COL / CONTACT_IDN / CARDS; candidate records
    CAND[1..nc] reused; SORT_HS / SORT_REST reused; by_range comparator;
    to_screen / bra_of / be_of are file-level functions (were closures
    made every update); waypoint labels cached on the point (_sa_lbl).
  * packet parser: one field table for all lines (a non-number field is
    skipped and the next moves up, exactly as before).
  * MSN RTE plan made again only when PL.route_sig() of the points
    changes (the export sends a new route table with every packet).
  * dl_tac.lua: the "used" table is cleared, not made new every update.
  * measured with the test rig (40 contacts, 16 SAMs, 20 waypoints):
    SA 21 -> 4.5 KB per update, HSI 22 -> 3.9, NAV page part ~3 KB; what
    is left is mostly the packet parser (new data once a second).
Export work spread over frames (MiG29DL_Export.lua, DL.spread)
  * tick() runs packet_job() in a coroutine (JOB); build_picture runs in
    its own coroutine inside it (run_picture: the same as the pcall it
    replaced - an error gives ok = false and the radar-only fallback).
    spread_point(cost) yields while SPREAD.on: after the world scan (its
    own frame), per object (1 / spread_objects), per terrain check
    (n / spread_samples, before its pcall: Lua 5.1 cannot yield across a
    pcall), per aircraft in the AWACS and assemble loops, per SAM site.
  * (first version: slices grown by a work estimate - replaced by time
    slices, see below). Paused sim: no new model time, nothing runs.
  * reset_state() drops a running JOB. DL.spread = false = the old
    behaviour (also when the Lua state has no coroutine library).
  * test rig (fixD/t_spread.py): 300 air / 3000 ground longest frame
    6.4 -> 1.0 ms, 500 / 5000 9.2 -> 2.1 ms; packets byte-identical.
    The old fixD tests step one frame per model second: with spreading a
    packet then takes seconds; *_fps.py copies step 50 frames per second
    and give the same output as before.
v1.8.2 export perf pass (ported from the F-15C SIT add-on, same code base)
  * scan_gap(): busy (SCAN.big) gap between world scans = 0.5 s per ms of
    SCAN.ema, clamped 2..6 s (DL.big_scan_gap_*); used by scan_due() and
    due(). Not busy: DL.period (every packet). big_scan_period unused.
  * MIG29SITG: dl_device poll_udp uses receivefrom and remembers the
    source of "MIG29DL 1" / "MIG29DLV" packets (the export's connected
    socket); sit_tick() (from net_tick) sends "MIG29SITG,1|0" back to it
    on every change and once a second while export packets came in the
    last 5 s. 1 = DL_BOOT on and DL_PAGES.mode 1 (SA/map), 9 (FLT),
    14 (PICTURE), or DL_TAC.intc running. Export: sit_poll() in our_after
    (every 0.1 s, never opens the socket), sit_paused(): last word 0 and
    younger than DL.sit_timeout (3) s -> scan_due false -> reuse_picture.
    settings.lua dl_pause_off_page = false (read with perf_log) = off.
  * re-hook: DCS's export has no debug library, in_chain = nil. Now:
    LuaExportBeforeNextFrame wrapper sets RUN.frames; check_attached
    re-wraps only if RUN.frames and not RUN.ran and in_chain ~= true;
    start_attach only if in_chain == false; rehook() caps at 20 per
    mission (reset_state), each logged. Tests: devtools/t_export_perf.py,
    devtools/t_sit_device.py, t_load_chain.py.
Busy missions (MiG29DL_Export.lua, DL.big_scan)
  * second log flight (busy server): our Lua work was spread fine, but
    the frame with LoGetWorldObjects itself took 4-5 ms (worst 11) and
    made ~1.1 MB of Lua table, once a second. That C call cannot be split.
  * scan_timed(): os.clock around the call, average 0.7 / 0.3; SCAN.big
    at >= big_scan_ms (3), back below 2/3 of it (log line on each switch).
  * scan_due(): with SCAN.big a full build_picture only every
    big_scan_period (2) s; the packets in between (still every DL.period:
    the cockpit lines) use reuse_picture(): SCAN.list again with age + dt
    (the cockpit dead-reckons by age, max_extrapolate_s), own radar fresh
    (radar_typ() for world contacts it now sees, base_typ back for the
    ones it lost), threats' distance again, FLIGHT entries moved on by
    vel[]. Items carry id / base_typ / own for this (not sent).
  * due() keeps the AWACS / f2f / threat periods in seconds while
    SCAN.big (every = period / big_scan_period scans).
  * after the scan a yield always (also with big slices): the scan frame
    is only the C call.
  * point 3 of the first list ("write only changed values") turned out
    to be there already: every P() / S() / set() handle compares with the
    last value. An SA update with 40 contacts makes ~91 real writes, the
    contacts' x / y (they move).
  * third log flight (busy server, big_scan on): the switch worked (scans
    15 per 30 s instead of 30), but 4-7 datalink frames per 30 s took
    4-18 ms. Causes found in the test rig: (1) the in-between packets did
    no spreading work, set SPREAD.last_work to ~0, so the next scan packet
    ran with scale 1, hit spread_max_frames and did the rest at once - now
    only a packet with a scan (SPREAD.scanned) sets last_work; (2)
    reuse_picture and the FLIGHT list loop ran in one frame - now both
    through run_spread() (was run_picture, now any function) with yield
    points; (3) the SAM dedupe compare at the end of build_picture grows
    with the square of the sites - yield points too. fixD/t_bigspike.py:
    worst frame without the scan 150/1500 3.3 -> 2.7 ms, 400/4000 2.8 ->
    2.3 ms (frames > 2 ms 4 -> 1); 1000/10000 13 -> 5-6 ms (what is left
    there: sorts and the packet text, not split).
  * fourth log flight: still 2-13 frames of 4-18 ms per 30 s. The work
    estimate (slices = last packet's work / 16) also grew the terrain
    share of a slice: up to ~540-900 LoGetAltitude samples in one frame
    (fixD/t_bigspike2.py counts them; terrain made slow on purpose).
    Replaced by TIME slices: spread_point() yields once spread_ms (1) has
    passed since SPREAD.t0 (set before every resume), looking at the clock
    every 0.02 cost units; spread_max_frames 90. SPREAD.scale / work /
    last_work / scanned and DL.spread_frames are gone. Rig: frames > 4 ms
    outside the scan 0-1 (were up to 7); scan every second, 500 / 5000:
    worst frame 1.2 ms (was 2.1); packets still byte-identical.
  * test: fixD/t_bigscan.py (moving world, scan made slow on purpose):
    packets every second, full scan every 2 s, contacts within 60 m of
    the every-second picture, AWACS still 6 s, radar fresh; switching
    back when the scan is cheap again.
Timing log, only with perf_log = true (settings.lua; default false):
  * cockpit: DL/dl_prof.lua, loaded at the end of dl_device.lua only when
    CFG.perf_log is set; it wraps the global update() (DCS calls it as
    before). Three marks inside update() - DL_PROF.mark(1) after net_tick,
    (2) after boot_tick, (3) before DL_PAGES.update - written as
    "if DL_PROF_ON then ... end": globals, so update() keeps 55 upvalues.
    Rows: BOOT = returned before mark 2 (off / starting), WAIT = after it
    but before mark 3 (MFD page 0, a text page between its 4 Hz updates,
    no sensors), else the page by DL_PAGES.mode. Sections net / boot /
    scope / pages only for the calls that reached mark 3.
  * export and hook: the same small logger copied into each file
    (perf_read_setting reads perf_log from settings.lua itself: they do
    not load dl_config.lua). Export rows "datalink" (tick) and "rwr"
    (rwr_tick), one frame count per LuaExportAfterNextFrame = the sim's
    frames per second; "dl scan" = the frames in which LoGetWorldObjects
    ran). Hook row "hook" (onSimulationFrame).
  * Logs: Saved Games\DCS\Logs\mig29dl_perf.log, mig29dl_export_perf.log,
    mig29dl_hook_perf.log; the file before is kept as .old.log; 480
    blocks (4 h) at most.
  * os.clock steps in 1 ms on Windows: single calls read 0 or 1 ms, the
    average over a block is right (random phase). "clock step" in the
    header row = the smallest step seen. "alloc" = collectgarbage("count")
    grown inside the call (calls in which the collector ran are left out).
  * tests: qa/perf/t_perf.py (simulated clock), qa/alloc/equiv.py (SA
    display values the same as before, also right after another page),
    qa/alloc/intc_nav.py (intercept kept 90 s on NAV).


v1.7.6
------
Only the DL scripts changed (dl_config, dl_device, dl_page, dl_pages,
dl_pages_dev); the export, hook and KRN-file insertions are as in v1.7.5.
Night palette (dl_page.lua): shipped in v1.7.6 and broken there (none of
  our pages was drawn, the cause is under "v1.7.7" below); switched off in
  the fixed v1.7.6 upload, on again (fixed) in v1.7.7.
  * every element whose material / font colour is in NIGHT_MAT gets the
    controller {"change_color_when_parameter_equal_to_number", k, 1, r, g,
    b} on the cockpit parameter DLP_NIGHT (1 = night), added in the wrapped
    Add (see v1.7.7). dl_pages_dev sets DLP_NIGHT from M.night (D/N
    switch); CFG.night_palette = false leaves the rule off.
    brightness_night default 4 -> 5.
SA labels, SYM 2 GROUP / 3 ALT (dl_device.lua, LB / LAY / label_pass)
  * contacts of one colour closer than label_group_dist (0.11 page units)
    share one label "<n>X ..." over the one nearest the jet; each label
    then takes the spot (above / below / left / right ...) that covers
    the least of the labels already placed (x3), the other symbols and
    the jet's symbol. Worked out on a new contact list, a scale / SYM
    change, or every 0.5 s; offsets go out as DL_C<n>_TX / _TY (move
    controllers on the label's own point in dl_page.lua). ~0.35 ms with
    40 contacts.
SA cursor: full square of half size symbol_size * cursor_box (1.45); the
  radar lock box stays at 1.9.
HSI: DLP_HSI_NX1..3 = steerpoint + next two route points
  ("%-3s %-6s %03dT %5s %s": label, name, true bearing, distance, ETA)
  centred under the rose; HDG / CRS readouts moved to the right (y 0.98 /
  0.88).
STORES page (dl_pages.lua mode 11, dl_pages_dev.lua upd_sms)
  * jet seen from behind, drawn in metres (K = 0.92 / 5.68 page units per
    m), traced from photos: wing, tailplane, fins, spine, tail deck, chute
    tube, curved underside, nozzles. Stations at SXM (m from the centre
    line); stations 1-3 / 5-7 have a bent leader line out to an even
    column CX at depth DROP; station 4 (centre tank) hangs directly under
    the underside (CFG.sms_tank_on_jet = false: on a line like the rest).
    No station numbers on the jet.
  * per station DLP_SMS_I<k> (shape 1-6: AAM, big AAM, tank, bomb, pod,
    other x selected), DLP_SMS_N<k> name (store_short: "R-27R",
    "PTB-1500" ...), DLP_SMS_C<k> count, DLP_SMS_A<k> selected (amber).
  * bottom lines: SMS_SEL, GUN, CM, total.
Tests: the v1.7.5 suite (runsuite.sh) gives the same results; SMS
garbage per update unchanged (~4.3 KB).


v1.7.7
------
Night palette, what went wrong in v1.7.6 and the fix (dl_page.lua)
  * In DCS, CreateElement gives a userdata; table fields set on it READ
    BACK AS TEXT (e.element_params, e.controllers, e.material are strings;
    logged in the sim 8 Nov 2026). v1.7.6's Add() wrapper read them back
    and ipairs() failed on the first coloured element - KRN's pcall around
    dl_page.lua swallowed the error, so none of our pages was built.
  * Now, while dl_page.lua / dl_pages.lua build, CreateElement returns a
    plain Lua table {__dl_cls = class}; the wrapped Add() adds the night
    rule from those plain tables (add_night), then makes the real element
    with the original CreateElement, copies the fields (FIELD_ORDER first,
    then the rest) and calls the original Add. The whole page build runs in
    DL_build_page() under pcall: the originals are put back after it in any
    case, and an error is written to mig29dl_page.log (it used to vanish in
    KRN's pcall). Nothing is ever read back from a DCS element.
  * The rule itself works as expected in DCS (tested 8 Nov: squares and
    text, alone and after a parameter_in_range): {"change_color_when_
    parameter_equal_to_number", param index, 1, r, g, b}, colours 0..1
    (0..255 overflows to white); the colour comes back by itself at 0.
  * Test rig: harness/ind_harness3.py makes elements behave like DCS
    (fields read back as text) - v1.7.6's dl_page builds 396 elements
    there, v1.7.7 all 5105 (4478 with the night rule).
STORES selection (dl_pages_dev.lua upd_sms)
  * LoGetPayloadInfo().CurrentStation is always 0 in the MiG-29. The
    External Stores switch (cockpit argument 29: 0 INBD, 1 OUTBD) picks a
    pair: INBD 3 / 5; OUTBD 2 / 6, then 1 / 7 once 2 and 6 are empty (as
    the jet fires, confirmed by the player). Only loaded non-tank stations
    of the pair are selected; the move to 1 / 7 happens when nothing at
    all is loaded on 2 / 6. CurrentStation > 0 still wins (other jets).
HSI route strip / FPL list: the route timing (M.ti, tot_calc) used to be
  worked out on the NAV page only, so their ETAs went stale; now it is
  also refreshed once a second on the HSI and the FPL view, and the HSI
  adds the timing's own clock (R.tod) to its seconds.
    CFG.sms_switch_arg overrides 29.
Options: mig29dl_map default true (optionsDb.lua, options.dlg state, DEF
  in dl_config.lua). DCS keeps a value the player already saved.
